package com.example.taluo.common;

import com.example.taluo.entity.dto.gamedto.Message;
import com.example.taluo.entity.dto.gamedto.Player;
import com.example.taluo.enums.MessageType;
import com.example.taluo.logic.GameRoom;
import com.example.taluo.logic.GameRoomManager;
import com.example.taluo.service.RoomService;
import com.example.taluo.utils.JsonUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.Getter;
import org.apache.rocketmq.shaded.com.google.gson.JsonObject;
import org.apache.rocketmq.shaded.com.google.gson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/*** @Author supersaiya
 * @Description 匹配玩家

 * @Date 2025/2/17 15:00

 * @Version 1.0*/

@Getter
public class MatchHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 维护一个队列，用于存储待匹配的玩家
    private static final Queue<Channel> waitingQueue = new ConcurrentLinkedQueue<>();

    // 用户名和用户ID的属性键
    // 维护一个映射，用于存储玩家的 userId 和 Channel
    private static final Map<String, Player> players = new ConcurrentHashMap<>();

    // 处理消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String content = msg.text();
        System.out.println("Received message in MatchHandler: " + content);

        try {
            Map<String, Object> message = JsonUtil.fromJson(content, Map.class);
            String type = (String) message.get("type");

            if ("MATCH_REQUEST".equals(type)) {
                // 获取用户名和用户ID
                String username = (String) message.get("username");
                String userId = (String) message.get("userId");
                if (username == null || userId == null) {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(Map.of(
                            "type", "ERROR",
                            "reason", "Username and userId are required."
                    ))));
                    return;
                }

                // 创建 Player 对象并存储到映射中
                Player player = new Player(userId, username, ctx.channel());
                players.put(userId, player);

                if (!waitingQueue.contains(ctx.channel())) {
                    waitingQueue.add(ctx.channel());
                    System.out.println("Player added to queue: " + ctx.channel().hashCode());
                    tryMatch(ctx.channel());
                } else {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(Map.of(
                            "type", "ERROR",
                            "reason", "Already in queue."
                    ))));
                }
            } else {
                ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(Map.of(
                        "type", "ERROR",
                        "reason", "Unknown message type."
                ))));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtil.toJson(Map.of(
                    "type", "ERROR",
                    "reason", "Invalid message format."
            ))));
        }
    }

    // 尝试匹配
    private void tryMatch(Channel channel) {
        if (waitingQueue.size() >= 2) {
            Channel player1 = waitingQueue.poll();
            Channel player2 = waitingQueue.poll();

            if (player1 == null || player2 == null) {
                System.out.println("Failed to poll two players from the queue.");
                return;
            }

            if (player1.equals(player2)) {
                System.out.println("Same player detected.");
                waitingQueue.add(player1);
                waitingQueue.add(player2);
                return;
            }

            // 获取玩家的 userId 和 username
            String userId1 = null;
            String username1 = null;
            for (Player player : players.values()) {
                if (player.getChannel().equals(player1)) {
                    userId1 = player.getUserId();
                    username1 = player.getUsername();
                    break;
                }
            }

            String userId2 = null;
            String username2 = null;
            for (Player player : players.values()) {
                if (player.getChannel().equals(player2)) {
                    userId2 = player.getUserId();
                    username2 = player.getUsername();
                    break;
                }
            }

            // 匹配成功
            String roomId = UUID.randomUUID().toString();
            GameRoom gameRoom = new GameRoom(roomId);
            gameRoom.addPlayer(userId1, player1);
            gameRoom.addPlayer(userId2, player2);
            gameRoom.startGame();

            GameRoomManager.addGameRoom(roomId, gameRoom);
            String matchSuccessMessage = JsonUtil.toJson(Map.of(
                    "type", "MATCH_SUCCESS",
                    "roomId", roomId
            ));

            player1.writeAndFlush(new TextWebSocketFrame(matchSuccessMessage));
            player2.writeAndFlush(new TextWebSocketFrame(matchSuccessMessage));

            System.out.println("Match successful for players: " + username1 + " (" + userId1 + ") and " + username2 + " (" + userId2 + ") in room: " + roomId);
        } else {
            System.out.println("Not enough players in queue to match. Current size: " + waitingQueue.size());
        }
    }
}